#include "word.h"
#include <QString>
#include <QJsonObject>
#include <QJsonArray>
#include <QList>

namespace WordMemory
{
    Example::Example(int id, const QString &example, const QString &translation)
        : id(id), example(example), translation(translation)
    {}

    QJsonObject Example::toJson() const
    {
        QJsonObject json;
        json["id"] = id;
        json["example"] = example;
        json["translation"] = translation;
        return json;
    }

    Example Example::fromJson(const QJsonObject &json)
    {
        return Example(
            json["id"].toInt(),
            json["example"].toString(),
            json["translation"].toString());
    }


    Word::Word(int id,
         const QString &word,
         const QString &meaning,
         const QList<Example> &examples,
         const QStringList &mnemonics,
         bool isFavorite)
        : id(id), word(word), meaning(meaning), examples(examples), mnemonics(mnemonics), isFavorite(isFavorite)
    {}

    QJsonObject Word::toJson() const
    {
        QJsonObject json;
        json["id"] = id;
        json["word"] = word;
        json["meaning"] = meaning;
        QJsonArray examplesArray;
        for (const auto &example : examples) {
            examplesArray.append(example.toJson());
        }
        json["examples"] = examplesArray;

        QJsonArray mnemonicsArray;
        for (const auto &mnemonic : mnemonics) {
            examplesArray.append(mnemonic);
        }
        json["mnemonics"] = mnemonicsArray;
        json["is_favorite"] = isFavorite;
        return json;
    }

    Word Word::fromJson(const QJsonObject &json)
    {
        QList<Example> examples;
        QJsonArray examplesArray = json["examples"].toArray();
        for (const auto &item : examplesArray) {
            examples.append(Example::fromJson(item.toObject()));
        }

        QStringList mnemonics;
        QJsonArray mnemonicsArray = json["mnemonics"].toArray();
        for (const auto &item : mnemonicsArray) {
            mnemonics.append(item.toString());
        }
        return Word(
            json["id"].toInt(),
            json["word"].toString(),
            json["meaning"].toString(),
            examples,
            mnemonics,
            json["is_favorite"].toBool(false));
    }
}
